/*
 * Copyright (C) 2008 GeoScheduler Team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */
package org.geoscheduler.rest;

import java.util.List;

import javax.annotation.Resource;
import javax.ws.rs.ConsumeMime;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.ProduceMime;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geoscheduler.commons.marshaller.MarshallingIterator;
import org.geoscheduler.commons.msgs.BasicMessageSeverities;
import org.geoscheduler.commons.msgs.ParametrizedMessage;
import org.geoscheduler.commons.msgs.types.EventMsgs;
import org.geoscheduler.commons.msgs.types.SecurityMsgs;
import org.geoscheduler.dao.EventDAO;
import org.geoscheduler.dao.LocationDAO;
import org.geoscheduler.exceptions.GSAuthorizationException;
import org.geoscheduler.model.Account;
import org.geoscheduler.model.Event;
import org.geoscheduler.model.Location;
import org.geoscheduler.model.dto.EventQueryDTO;
import org.geoscheduler.rest.utils.MIMEConstants;
import org.json.JSONObject;

/**
 * AccountEvents REST resource
 * 
 * @author lko
 * @author srakyi
 */
@Resource
@Path("events")
public class EventsResource extends AbstractAccountDependantResource {

	private final Log LOG = LogFactory.getLog(EventsResource.class);

	public EventsResource() {
		super();
	}

	@GET
	@Path("{login}")
	@ProduceMime(MIMEConstants.APP_JSON)
	public JSONObject getAllPrivateEvents(@PathParam("login") String login, @HeaderParam("Authorization") String auth) {
		try {
			Account account = authorize(auth, login, null);
			
			List<Event> events = getEventDAO().loadByIdAccount(account.getId());
			return response(new MarshallingIterator<Event>(events.iterator(), getMarshaller()));
		} catch (GSAuthorizationException ex) {
			return response(new ParametrizedMessage(SecurityMsgs.ILLEGAL_ACCESS, BasicMessageSeverities.ERROR, ex.getMessage()));
		} catch (Exception ex) {
			LOG.error("failed to get events for account " + login, ex);
			return response(ex);
		}
	}

	/**
	 * Stores private or public event for user identified by login.
	 * 
	 * TODO only one (primary) location is supported.
	 * 
	 * @param login	Login of event owner (retrieved from URL).
	 * @param auth		Authorization information (retrieved from HTTP header).
	 * @param json		{@link JSONObject} with {@link Event} to be stored.
	 * @return
	 */
	@PUT
	@Path("{login}")
	@ConsumeMime(MIMEConstants.APP_JSON)
	@ProduceMime(MIMEConstants.APP_JSON)
	public JSONObject updatePrivateEvent(@PathParam("login") String login, @HeaderParam("Authorization") String auth, JSONObject json) {
		try {
			Account account = authorize(auth, login, json);
			
			EventDAO eDAO = getEventDAO();
			Event event = getMarshaller().unmarshall(new Event(), json);
			
			// set proper account id before storing event
			if (event.getIdAccount().longValue() != account.getId().longValue()) {
				return response(new ParametrizedMessage(SecurityMsgs.ILLEGAL_ACCESS, BasicMessageSeverities.ERROR, "Attemt to PUT other user's event."));
			} else {
				event.setIdAccount(account.getId());
			}
			
			if (event.getId() == null) {
				Event resultEvent = eDAO.insert(event);
				storeLocation(resultEvent, event.getLocation());
				return response(resultEvent);
			} else {
				Event resultEvent = eDAO.update(event);
				if (resultEvent == null) {
					return response(new ParametrizedMessage(EventMsgs.INVALID_EVENT_ID, BasicMessageSeverities.ERROR));
				}
				clearAndStoreLocation(resultEvent, event.getLocation());
				return response(resultEvent);
			}
		} catch (GSAuthorizationException ex) {
			return response(new ParametrizedMessage(SecurityMsgs.ILLEGAL_ACCESS, BasicMessageSeverities.ERROR, ex.getMessage()));
		}  catch (Exception ex) {
			LOG.error("Failed to PUT event for account " + login, ex);
			return response(ex);
		}
	}
	
	/**
	 * Sets given {@link Location} as primary location of given event and persists location into database.
	 * 
	 * @param event			{@link Event} to set primary location into.
	 * @param primaryLocation	{@link Location} to be set and persisted.
	 */
	private void storeLocation(Event event, Location primaryLocation) {
		if (primaryLocation != null) {
			primaryLocation.setPrimaryLocation(1);
			primaryLocation.setIdEvent(event.getId());
			
			LocationDAO lDAO = getLocationDAO();
			if (primaryLocation.getId() == null) {
				event.setLocation(lDAO.insert(primaryLocation));
			} else {
				event.setLocation(lDAO.update(primaryLocation));
			}
		} else {
			event.setLocation(null);
		}
	}
	
	private void clearAndStoreLocation(Event event, Location primaryLocation) {
		if (primaryLocation != null) {
			LocationDAO lDAO = getLocationDAO();
			lDAO.deletePrimaryLocation(event.getId());
			
			storeLocation(event, primaryLocation);
		} else {
			// TODO shouldn't we try to find previous primary location?
		}
	}
	
	@POST
	@Path("{login}")
	@ConsumeMime(MIMEConstants.APP_JSON)
	@ProduceMime(MIMEConstants.APP_JSON)
	public JSONObject queryPrivateEvents(@PathParam("login") String login, @HeaderParam("Authorization") String auth, JSONObject jsonQuery) {
		try {
			Account account = authorize(auth, login, jsonQuery);
			
			EventQueryDTO eventDTO = getMarshaller().unmarshall(new EventQueryDTO(), jsonQuery);
			eventDTO.setAccount(account);
			
			List<Event> events = getEventDAO().query(eventDTO);
			return response(new MarshallingIterator<Event>(events.iterator(), getMarshaller()));
		} catch (GSAuthorizationException ex) {
			return response(new ParametrizedMessage(SecurityMsgs.ILLEGAL_ACCESS, BasicMessageSeverities.ERROR, ex.getMessage()));
		} catch (Exception ex) {
			LOG.error("Failed to query private events ", ex);
			return response(ex);
		}
	}
	
	@POST
	@ConsumeMime(MIMEConstants.APP_JSON)
	@ProduceMime(MIMEConstants.APP_JSON)
	public JSONObject queryPublicEvents(JSONObject jsonQuery) {
		try {
			EventQueryDTO eventDTO = getMarshaller().unmarshall(new EventQueryDTO(), jsonQuery);

			List<Event> events = getEventDAO().query(eventDTO);
			return response(new MarshallingIterator<Event>(events.iterator(), getMarshaller()));
		} catch (Exception ex) {
			LOG.error("failed to get public events " + null, ex);
			return response(ex);
		}
	}

}
